<template>
  <el-card>
    <el-button type="primary" :icon="Plus" @click="showSaveDialog"
      >添加品牌</el-button
    >
    <!-- 添加品牌的弹框 -->
    <el-dialog v-model="visible" :title="`${trademarkFormData.id ? '修改' : '添加'}品牌`">
      <!-- 弹框From表单 -->
      <!-- 
      :model:表单所有数据
      rules:表单校验规则
     -->

      <el-form
        :model="trademarkFormData"
        ref="trademarkFormRef"
        :rules="trademarkFormRules"
        label-width="90px"
      >
        <!-- 
      prop:使用那个校验规则
     -->
        <el-form-item label="品牌名称" prop="tmName">
          <!--收集表单数据 -->
          <el-input v-model="trademarkFormData.tmName" />
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/app-dev/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkFormData.logoUrl"
              :src="trademarkFormData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload> </el-form-item
      ></el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible=false">取消</el-button>
          <el-button type="primary" @click="submitFrom">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 
      el-table
        data 要渲染的数据
        border 带边框

        el-table-column 列
          type="index" 渲染序号
          label 列的标题
          width 列宽
          align 对齐方式
          prop 要渲染数据中哪个属性的值

          如果只要渲染纯数据，直接prop
          如果要渲染的一些其他结构（组件），用默认插槽
    -->
    <el-table :data="trademarkList" border class="trademark-table">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" :alt="row.tmName" class="trademark-img" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <!-- 
          默认插槽 + 作用域插槽
            scope
              $index: 要渲染数据的下标
              row:    要渲染的整个数据
         -->
        <template #default="{row}">
          <!-- <template v-slot="scope"> -->
          <el-tooltip content="修改品牌" placement="top" effect="light">
            <el-button
              size="small"
              type="warning"
              :icon="Edit"
              @click="showUpdateTrademark(row)"
            />
          </el-tooltip>

          <el-tooltip content="删除品牌" placement="top" effect="light">
            <el-button size="small" type="danger" :icon="Delete" @click="delTrademark(row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 
      v-model:currentPage 当前页码
      v-model:page-size   每页条数
      page-sizes  可以选择每页条数的值
      layout 放入需要使用的组件
      total 总数
      @current-change  当currentPage发生变化时触发
      @size-change     当page-size发生变化时触发
    -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="prev, pager, next, jumper, total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'XTrademark',
}
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getTrademarkListApi, saveTrademarkApi,updateTrademarkApi,removeTrademarkApi} from '@/api/product/trademark'
import type { TrademarkList,TrademarkItem } from '@/api/product/model/trademarkModel'
// import { ElMessageBox } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
import { ElMessage ,ElMessageBox} from 'element-plus'
import { trigger } from '@vue/reactivity'

// 删除品牌
const  delTrademark = (row:TrademarkItem)=>{

  ElMessageBox.confirm(
    `你确定要删除${row.tmName}数据吗？`,
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then( async() => {
      await removeTrademarkApi(row.id);
    ElMessage.success(`删除${row.tmName}成功`);
    getTrademarkList(); // 重新获取数据展示
    })
    // .catch(() => {
    //   ElMessage({
    //     type: 'info',
    //     message: 'Delete canceled',
    //   })
    // })

}
// 显示添加的对话框
const showSaveDialog = ()=>{
  visible.value = true 
  trademarkFormData.tmName = ''
  trademarkFormData.logoUrl = ''
  trademarkFormData.id = 0
  trademarkFormRef.value?.clearValidate()
}
// 显示修改对话框
const showUpdateTrademark = (row:TrademarkItem)=>{
  visible.value = true
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  trademarkFormData.id = row.id
}
// 对话框显示隐藏
const visible = ref(false)

// 控制弹框
// const dialogVisible = ref(false)
// const handleClose = (done: () => void) => {
//   ElMessageBox.confirm('Are you sure to close this dialog?')
//     .then(() => {
//       done()
//     })
//     .catch(() => {
//       // catch error
//     })
// }

// onload上传图片、

const imageUrl = ref('')
// 图片上传成功的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  trademarkFormData.logoUrl = response.data
}
// 图片上之前触发的函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // rawFile 上传的图片文件
  // rawFile.type 图片类型
  // rawFile.size 图片大小
  const typeFiles = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
  if (!typeFiles.includes(rawFile.type)) {
    ElMessage.error('上传图片格式必须是jpg或png或gif!')
    return false // 不会上传图片
  } else if (rawFile.size / 1024 > 2000) {
    ElMessage.error('上传图片大小不能超过2000kb!')
    return false
  }
  return true // 继续上传图片
}
// 表单项
const form = ref()
// 定义表单收集数据
const trademarkFormData = reactive({
  tmName: '',
  logoUrl: '',
  id:0
})
// 定义表单校验规则
const trademarkFormRules = reactive<FormRules>({
  tmName: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
  logoUrl: [{ required: true, message: '请上传品牌图片', trigger: 'blur' }],
})
// ref语法的用法，用来获取组件实例对象
const trademarkFormRef = ref<FormInstance>()

const submitFrom = () => {
  // / 触发表单校验
  // value?.validate可连链语法，value有值就会调用validate,没有值就不会触发
  trademarkFormRef.value?.validate(async (valid) => {
    if (valid) {
      const { tmName, logoUrl,id } = trademarkFormData
      
      //清空表单数据
      if(id){
     await updateTrademarkApi({ tmName, logoUrl, id })
      }else{
      await saveTrademarkApi(tmName, logoUrl)
      }
      
      ElMessage.success(`${id ? '修改' : '添加'} 品牌成功`)
      // 隐藏对话框
      visible.value = false
      // 重新发送请求，获取最新的数据展示（更新客户端数据）
      getTrademarkList()
    }
  })
}
// 品牌列表数据
const trademarkList = ref<TrademarkList>([])

// 当前页码
const currentPage = ref(2)
// 每页条数
const pageSize = ref(3)
// 总数
const total = ref(0)

// 封装函数一个请求函数 ，用来获取品牌列表

const getTrademarkList = async () => {
  const result = await getTrademarkListApi(currentPage.value, pageSize.value)
  trademarkList.value = result.records
  total.value = result.total
}
// 页面一上来就加载
onMounted(() => {
  getTrademarkList()
})

// 当currentPage发生变化时触发
const handleCurrentChange = (newCurrenPage: number) => {
  currentPage.value = newCurrenPage
  getTrademarkList()
}
// 当page-size发生变化时触发
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize
  getTrademarkList()
}
</script>

<style scoped>
/* 
  scoped:
    1. 让样式只对当前组件生效
    2. 自动删除没有引用的样式
*/
.trademark-table {
  margin: 20px 0;
}

.trademark-img {
  width: 150px;
  height: 100px;
}

.trademark-input {
  width: 300px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
